import { defineStore } from 'pinia';
import { ref, watch } from 'vue';
import { usePreferredDark } from '@vueuse/core';

export const useThemeStore = defineStore('theme', () => {
  // 检测系统主题偏好
  const prefersDark = usePreferredDark();

  // 获取本地存储的主题设置，如果没有则使用系统偏好
  const getDefaultTheme = () => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) return savedTheme;
    return prefersDark.value ? 'dark' : 'light';
  };

  // 当前主题状态
  const currentTheme = ref(getDefaultTheme());

  // 切换主题方法
  function toggleTheme() {
    currentTheme.value = currentTheme.value === 'light' ? 'dark' : 'light';
  }

  // 设置特定主题
  function setTheme(theme) {
    if (theme === 'light' || theme === 'dark') {
      currentTheme.value = theme;
    }
  }

  // 监听主题变化，应用到DOM并保存到本地存储
  watch(
    currentTheme,
    (newTheme) => {
      // 更新DOM
      if (newTheme === 'dark') {
        document.body.classList.add('dark-theme');
      } else {
        document.body.classList.remove('dark-theme');
      }

      // 保存到本地存储
      localStorage.setItem('theme', newTheme);
    },
    { immediate: true }
  );

  // 监听系统主题变化
  watch(prefersDark, (newValue) => {
    // 只有当用户没有手动设置过主题时，才跟随系统主题
    if (!localStorage.getItem('theme')) {
      currentTheme.value = newValue ? 'dark' : 'light';
    }
  });

  // 初始化主题方法
  function initTheme() {
    // 应用当前主题
    if (currentTheme.value === 'dark') {
      document.body.classList.add('dark-theme');
    } else {
      document.body.classList.remove('dark-theme');
    }
  }

  return {
    currentTheme,
    toggleTheme,
    setTheme,
    initTheme,
  };
});
